/** 块函数
 * @ 标  识: hchhIOT
 * @ 作  者: 阿拉丁矿工 黄传鸿 <hchhyzc@foxmail.com>
 */

/* ================================================================================================ */
// 🍀引入
/* ================================================================================================ */
import * as d3 from "d3"
import axios from "axios"
import { useMessage } from 'naive-ui';
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// 🐸 图元端函数引入
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
import {
  onRecordLog,//记录日志
  onGetUUID,
  onSetElementCont,
  onGetElementCont,
  onActionRightNavigation,
} from "@/functions"

/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// 🐸 引入存储
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
import { useCanvasStore } from "@/store/canvasStore"; // 画布
import { useWorkStore } from "@/store/workStore"; // 工作数据
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// 🐸 使用存储
/**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
const canvasStore = useCanvasStore(); // 画布
const workStore = useWorkStore(); // 设备数据
const message = useMessage()// 消息

/* ================================================================================================ */
//                                函数
/* ================================================================================================ */

/** 选择当前块组 */
export const onSelectedBlockGroup = (blockGroup: any) => {
 // console.log("★ 选择当前块组")
  /** 日志处理器 */
  onRecordLog("选择块组 " + blockGroup.label)
 // console.log(blockGroup)
 // console.log(Object.keys(blockGroup.children).length)
  let long = Object.keys(blockGroup.children).length
  if (long !== 0) {
    canvasStore.selectedBlockGroup = blockGroup//选择的块组
    canvasStore.selectedBlock = canvasStore.selectedBlockGroup.children[0]//选择的块
    onActionRightNavigation("RightBlock") //激活右框导航
  }

}

/** 下载块组 */
export const onBlockGroupGet = () => {
 // console.log("㊣ 公共函数-获取工程列表")

  /** ★ 发送-工程数据 */
  axios({
    url: `/api/HCIOT?query=getBlockGroup`,
    method: 'get',
  })
    .then((response: any) => {
     // console.log(response.data)
      if (response.status === 200) {
        canvasStore.blockGroup = response.data
        /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
        // 🐸 提示 记录到日志
        /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
        onRecordLog("下载块组成功");

        try {
          if (canvasStore.blockGroup[0].children.length > 0) {
            canvasStore.selectedBlock = canvasStore.blockGroup[0].children[0]
          }
        } catch (error) {
        }
      }
    })
    .catch((error: any) => {
     // console.log("故障")
    })

}

/** 上载块组 */
export const onBlockGroupSave = () => {
 // console.log("㊣ 公共函数-保存工程")
  /** ★ 发送-工程数据 */
  axios({
    url: `/api/HCIOT?query=saveBlockGroup`,
    method: 'post',
    headers: { 'content-type': 'application/json' },
    data: canvasStore.blockGroup,
  })
    .then((response: any) => {
      if (response.status === 200) {
       // console.log(response.data)
        message.success('保存文件成功')
      }
    })
    .catch((error: any) => {
     // console.log("故障")
    })
}

/** 新建块组 */
export const onBlockGroupAdd = () => {
  // console.log("块函数-新建块组")
  /** 计数 */
  let BlockGroupCont = onSetElementCont(
    "BlockGroupCont",
    Number(onGetElementCont("BlockGroupCont")) + 1
  )
  /** 块组 */
  let NewBlockGroup = {
    label: '块组' + BlockGroupCont,
    key: 'blockGroup' + onGetUUID(),
    type: 'blockGroup',
    children: []
  }
  canvasStore.blockGroup.push(NewBlockGroup)
}

/** 删除块组 */
export const onBlockGroupDelete = (Key: string) => {
 // console.log("块函数-删除块组")
 // console.log(Key)
  let blockGroup = canvasStore.blockGroup
  /** 判断选择块组 */
  if (Key) {
    /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    // 🐸 遍历-全部块组
    /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    for (let index = 0; index < blockGroup.length; index++) {
      let element = blockGroup[index]
      /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
      // 🐸 判断是否是默认块组
      /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
      if (element.key === Key && element.key !== 'CustomBlockGroup') {
        blockGroup.splice(index, 1)
        canvasStore.selectedBlockGroup = {}
        message.success('块组已删除')
      } else {
        message.error('默认块组,不能删除')
      }
    }
  } else {
    message.error('没有选择块组')
  }
}

/** 剪切块 */
export const onBlockCut = (Block: any) => {
 // console.log("块函数-剪切块")
  /** 块  */
  let blockGroup = canvasStore.blockGroup
  /** 判断选择 */
  if (Block.key) {
    /** 复制块 */
    canvasStore.copyBlock = JSON.parse(JSON.stringify(Block))
    let NewKey = 'Block' + onGetUUID()
    canvasStore.copyBlock.key = NewKey
    canvasStore.copyBlock.label = onGetUUID()
   // console.log(canvasStore.copyBlock )
    message.success('已剪切')
    /** 遍历-块组 */
    for (let indexA = 0; indexA < blockGroup.length; indexA++) {
      let elementA = blockGroup[indexA]
      let Childrens = elementA.children
      /** 遍历-块 */
      for (let indexB = 0; indexB < Childrens.length; indexB++) {
        let elementB = Childrens[indexB]
        if (elementB.key === Block.key) {
          Childrens.splice(indexB, 1)
          canvasStore.selectedBlock = {}
        }
      }
    }
  } else {
    message.error('没有选择')
    canvasStore.copyBlock = {}
  }
}

/** 复制块 */
export const onBlockCopy = (Block: any) => {
 // console.log("块函数-复制块")
 // console.log(Block)
  /** 判断选择 */
  if (Block.key) {
    /** 复制块 */
    canvasStore.copyBlock = JSON.parse(JSON.stringify(Block))
    let NewKey = 'Block' + onGetUUID()
    canvasStore.copyBlock.key = NewKey
    canvasStore.copyBlock.label = onGetUUID()
   // console.log(canvasStore.copyBlock)
    message.success('已复制')
  } else {
    message.error('没有选择')
    canvasStore.copyBlock = {}
  }
}

/** 插入块 */
export const onBlockInsert = (Key: string) => {
 // console.log("块函数-插入块")
  if (canvasStore.copyBlock.key) {
    /** 块组  */
    let blockGroup = canvasStore.blockGroup
    /** 选择块 */
    let copyBlock = canvasStore.copyBlock
   // console.log(copyBlock)
    // 遍历块组
    blockGroup.forEach((item: any) => {
      if (item.key === Key) {
        item.children.push(copyBlock)
        canvasStore.copyBlock = {}
      }
    })
  } else {
    message.error('没有块')
  }
}

/** 删除块 */
export const onBlockDelete = (Key: string) => {
 // console.log("块函数-删除块")
  /** 块组 */
  let blockGroup = canvasStore.blockGroup
  if (Key) {
    /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    // 🐸 遍历-块组
    /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    for (let indexA = 0; indexA < blockGroup.length; indexA++) {
      let elementA = blockGroup[indexA]
      let Childrens = elementA.children
      /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
      // 🐸 遍历-块
      /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
      for (let indexB = 0; indexB < Childrens.length; indexB++) {
        let elementB = Childrens[indexB]
        if (elementB.key === Key && Key !== 'CustomBlock') {
          Childrens.splice(indexB, 1)
          canvasStore.selectedBlock = {}
        } else {
          message.error('默认块,不能删除')
        }
      }
    }
  } else {
    message.error('没有选择')
  }

}

/** 建块 */
export const onCreateBlock = () => {
 // console.log("块函数-建块")
  /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  // 🐸 变量转储
  /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  /** 选中的id */
  let selectKeys = canvasStore.selectKeys
  /** 深度拷贝-视图数据 */
  let pels = JSON.parse(JSON.stringify(workStore.pels))
  /** 判断-选择集长度 */
  if (selectKeys.length > 0) {
    /** Html标签 */
    let htmlLabel = ``

    /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    // 🐸 遍历-选择集
    /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    for (let index = 0; index < selectKeys.length; index++) {
      /** 选中的id项 */
      const Key = selectKeys[index]
      /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
      // 🐸 ★ 遍历-视图数据
      /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
      for (let indexB = 0; indexB < pels.length; indexB++) {
        /** 图元参数*/
        let pelInfo = pels[indexB]
        /** 判断-选中的图元 */
        if (pelInfo.key === Key) {
          /** ★ ★ 获取图元类型 */
          let PelType = pelInfo.type
         // console.log(`图元类型=${PelType}`)
          /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
          // 🐸 ★ ★ 获取图元标签;去除为零的标签
          /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
          if (PelType === "horizontaLine"/*水平线*/) {
            let replaceStr = 'id=' + String(Key) + ' '
            let tempHtml = String(pelInfo.htmls).replace(replaceStr, '')
            tempHtml = tempHtml.replace(`stroke-dasharray='' `, '')
            tempHtml = tempHtml.replace(`stroke-dashoffset='0'`, '')
            htmlLabel = htmlLabel + tempHtml
          }
          if (PelType === "verticalLine"/*垂直线*/) {
            let replaceStr = 'id=' + String(Key) + ' '
            let tempHtml = String(pelInfo.htmls).replace(replaceStr, '')
            tempHtml = tempHtml.replace(`stroke-dasharray='' `, '')
            tempHtml = tempHtml.replace(`stroke-dashoffset='0'`, '')
            htmlLabel = htmlLabel + tempHtml
          }
          if (PelType === "slantLine"/*斜线*/) {
            let replaceStr = 'id=' + String(Key) + ' '
            let tempHtml = String(pelInfo.htmls).replace(replaceStr, '')
            tempHtml = tempHtml.replace(`stroke-dasharray='' `, '')
            tempHtml = tempHtml.replace(`stroke-dashoffset='0'`, '')
            htmlLabel = htmlLabel + tempHtml
          }
          if (PelType === "circle"/*圆*/) {
            let replaceStr = 'id=' + String(Key)
            let tempHtml = String(pelInfo.htmls).replace(replaceStr, '')
            tempHtml = tempHtml.replace(`stroke-dasharray='' `, '')
            tempHtml = tempHtml.replace(`stroke-dashoffset='0'`, '')
            htmlLabel = htmlLabel + tempHtml
          }
          if (PelType === "ellipse"/*椭圆*/) {
            let replaceStr = 'id=' + String(Key) + ' '
            let tempHtml = String(pelInfo.htmls).replace(replaceStr, '')
            tempHtml = tempHtml.replace(`stroke-dasharray='' `, '')
            tempHtml = tempHtml.replace(`stroke-dashoffset='0'`, '')
            htmlLabel = htmlLabel + tempHtml
          }
          if (PelType === "arc"/*三点弧线*/) {
            let replaceStr = 'id=' + String(Key) + ' '
            let tempHtml = String(pelInfo.htmls).replace(replaceStr, '')
            tempHtml = tempHtml.replace(`stroke-dasharray='' `, '')
            tempHtml = tempHtml.replace(`stroke-dashoffset='0'`, '')
            htmlLabel = htmlLabel + tempHtml
          }
          if (PelType === "circlePolygon" /*圆分多边形*/) {
            let replaceStr = 'id=' + String(Key)
            let tempHtml = String(pelInfo.htmls).replace(replaceStr, '')
            tempHtml = tempHtml.replace(`stroke-dasharray='' `, '')
            tempHtml = tempHtml.replace(`stroke-dashoffset='0'`, '')
            htmlLabel = htmlLabel + tempHtml
          }
          if (PelType === "rectangle" /*矩形*/) {
            let replaceStr = 'id=' + String(Key) + ' '
            let tempHtml = String(pelInfo.htmls).replace(replaceStr, '')
            tempHtml = tempHtml.replace(`stroke-dasharray='' `, '')
            tempHtml = tempHtml.replace(`stroke-dashoffset='0'`, '')
            htmlLabel = htmlLabel + tempHtml
          }
          if (PelType === "polygon" /*多边形*/) {
            let replaceStr = 'id=' + String(Key) + ' '
            let tempHtml = String(pelInfo.htmls).replace(replaceStr, '')
            tempHtml = tempHtml.replace(`stroke-dasharray='' `, '')
            tempHtml = tempHtml.replace(`stroke-dashoffset='0'`, '')
            htmlLabel = htmlLabel + tempHtml
          }
          if (PelType === "polyline" /*折线*/) {
            let replaceStr = 'id=' + String(Key) + ' '
            let tempHtml = String(pelInfo.htmls).replace(replaceStr, '')
            tempHtml = tempHtml.replace(`stroke-dasharray='' `, '')
            tempHtml = tempHtml.replace(`stroke-dashoffset='0'`, '')
            htmlLabel = htmlLabel + tempHtml
          }
          if (PelType === "path" /*路径*/) {
            let replaceStr = 'id=' + String(Key) + ' '
            let tempHtml = String(pelInfo.htmls).replace(replaceStr, '')
            tempHtml = tempHtml.replace(`stroke-dasharray='' `, '')
            tempHtml = tempHtml.replace(`stroke-dashoffset='0'`, '')
            htmlLabel = htmlLabel + tempHtml
          }
          if (PelType === "svgText" /*Svg文本*/) {
            onRecordLog("建块不包含 Svg文本")
            message.error("建块不包含 Svg文本")
          }
          if (PelType === "wrap" /*包*/) {
            onRecordLog("建块不包含 包")
            message.error("建块不包含 包")
          }
          if (PelType === "divBlock" /*DIV块*/) {
            onRecordLog("建块不包含 DIV块")
            message.error("建块不包含 DIV块")
          }
          if (PelType === "divText" /*DIV文本*/) {
            onRecordLog("建块不包含 DIV文本")
            message.error("建块不包含 DIV文本")
          }
          if (PelType === "svgImage" /*svg图片*/) {
            message.error("建块不包含 svg图片")
          }
        }

      }
    }
   // console.log(htmlLabel)
    /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    // 🐸 ★ 遍历-选择集
    /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    /** 新块 */
    let NewBlock = {
      label: '块' + onGetUUID(),
      key: 'Block' + onGetUUID(),
      type: 'divBlock',
      val: htmlLabel,
    }

    canvasStore.blockGroup[0].children.unshift(NewBlock)
  } else {
    message.error("未选择图元")
  }
  canvasStore.selectKeys = []//清理选择键
  canvasStore.selectToggle = !canvasStore.selectToggle// 触发-选择切换
}